
<!-- 表单登录组件 -->
<template>
    <van-form @submit="onSubmit">
        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]" />
        <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
    </van-form>
</template>

<script>
// 导入接口
import { loginApi } from '@/api/login'
import { Toast } from 'vant';
export default {
    data() {
        return {
            username: '',
            password: '',
        }
    },
    methods: {
        onSubmit(values) {
            console.log('submit', values);
            // 提交表单, 调用登录接口
            loginApi({
                loginname: values['用户名'],
                password: values['密码']
            }).then(res => {
                // console.log(res);
                if (res.code == 200) {
                    // 说明登录成功
                    // 01: 友好提示
                    Toast({
                        type: 'success',
                        message: res.message,
                        duration: 1000,
                        onClose: () => {
                            console.log('关闭后触发的函数');
                            // 02: 将token 存到本地
                            localStorage.setItem('token', res.data.token)
                            // 03: 将用户信息存到vuex 中
                            // console.log(this);
                            this.$store.commit('updateUser', res.data.userid)
                            // 04: 跳转新的页面
                            this.$router.push('/home')
                        }
                    });



                }

            })

        },
    }
}
</script>
<style scoped></style>